<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>火星情报局 - 管理控制台</title>
    <link rel="stylesheet" href="../admin-styles.css">
    <link rel="stylesheet" href="../api-config-styles.css">
    <link rel="stylesheet" href="../api-docs.css">
</head>
<body>
    <div class="admin-container">
        <aside class="sidebar">
            <div class="logo">
                <h1>火星情报局</h1>
            </div>
            <nav class="main-nav">
                <ul>
                    <li class="active"><a href="#" data-view="ai-roles">🤖 AI角色管理</a></li>
                    <li><a href="#" data-view="api-keys">🔑 API密钥管理</a></li>
                    <li><a href="#" data-view="api-config">⚙️ API密钥配置</a></li>
                    <li><a href="#" data-view="users">👥 用户管理</a></li>
                    <li><a href="#" data-view="shared-images">🖼️ 社区图片管理</a></li>
                    <li><a href="#" data-view="file-management">📁 文件管理</a></li>
                    <li><a href="#" data-view="system">🔧 系统设置</a></li>
                </ul>
            </nav>
            <div class="user-info">
                <span id="currentUser">管理员</span>
                <button id="logoutBtn" class="btn-logout">退出登录</button>
            </div>
        </aside>
        
        <main class="main-content">
            <header class="page-header">
                <h2 id="pageTitle">AI角色管理</h2>
                <div class="header-actions">
                    <button id="createAiRoleBtn" class="btn-primary">创建新角色</button>
                    <button id="createApiKeyBtn" class="btn-primary" style="display: none;">创建API密钥</button>
                    <button id="saveApiConfigBtn" class="btn-primary" style="display: none;">保存配置</button>
                    <button id="createUserBtn" class="btn-primary" style="display: none;">创建用户</button>
                    <button id="batchDeleteUsersBtn" class="btn-danger" style="display: none;">批量删除</button>
                    <button id="refreshSharedImagesBtn" class="btn-primary" style="display: none;">刷新列表</button>
                    <button id="cleanupFilesBtn" class="btn-primary" style="display: none;">清理文件</button>
                    <button id="refreshStatsBtn" class="btn-secondary" style="display: none;">刷新统计</button>
                </div>
            </header>
            
            <div class="content-container">
                <!-- AI角色列表视图 -->
                <div id="ai-roles-view" class="view active">
                    <div class="filter-bar">
                        <input type="text" id="searchAiRole" placeholder="搜索角色名称..." class="search-input">
                        <select id="filterAiRoleType" class="filter-select">
                            <option value="">所有类型</option>
                            <option value="assistant">通用助手</option>
                            <option value="tutor">教育导师</option>
                            <option value="entertainment">娱乐伙伴</option>
                            <option value="other">其他类型</option>
                            <option value="text-to-image">文生图</option>
                        </select>
                    </div>
                    
                    <div class="data-table-container">
                        <table class="data-table" id="aiRolesTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>头像</th>
                                    <th>名称</th>
                                    <th>类型</th>
                                    <th>API提供商</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="aiRolesTableBody">
                                <!-- JS填充内容 -->
                                <tr>
                                    <td colspan="7" style="text-align: center;">加载中...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="pagination" id="aiRolesPagination">
                        <!-- JS填充分页 -->
                    </div>
                </div>
                
                <!-- API密钥管理视图 -->
                <div id="api-keys-view" class="view">
                    <div class="filter-bar">
                        <input type="text" id="searchApiKey" placeholder="搜索密钥名称..." class="search-input">
                        <select id="filterApiKeyProvider" class="filter-select">
                            <option value="">所有提供商</option>
                            <option value="openai">OpenAI</option>
                            <option value="claude">Claude</option>
                            <option value="gemini">Gemini</option>
                            <option value="other">其他</option>
                        </select>
                        <select id="filterApiKeyStatus" class="filter-select">
                            <option value="">所有状态</option>
                            <option value="active">启用</option>
                            <option value="inactive">禁用</option>
                        </select>
                    </div>
                    
                    <div class="data-table-container">
                        <table class="data-table" id="apiKeysTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>名称</th>
                                    <th>提供商</th>
                                    <th>状态</th>
                                    <th>使用次数</th>
                                    <th>最后使用</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="apiKeysTableBody">
                                <tr>
                                    <td colspan="8" style="text-align: center;">加载中...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="pagination" id="apiKeysPagination">
                        <!-- JS填充分页 -->
                    </div>
                </div>
                
                <!-- API密钥配置视图 -->
                <div id="api-config-view" class="view">
                    <div class="config-panel">
                        <h3>ET项目API密钥配置</h3>
                        <p class="config-description">
                            直接配置ET项目所需的API密钥，系统会自动创建或更新对应的密钥记录。
                        </p>
                        
                        <form id="apiConfigForm" class="config-form">
                            <!-- DeepSeek配置 -->
                            <div class="config-section">
                                <div class="section-header">
                                    <h4>🤖 DeepSeek AI 配置</h4>
                                    <span class="section-status" id="deepseekStatus">未配置</span>
                                </div>
                                <div class="form-group">
                                    <label for="deepseekApiKey">DeepSeek API密钥</label>
                                    <div class="input-with-toggle">
                                        <input type="password" id="deepseekApiKey" name="deepseek_key" 
                                               placeholder="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                                        <button type="button" class="toggle-visibility" data-target="deepseekApiKey">
                                            <span class="eye-icon">👁️</span>
                                        </button>
                                    </div>
                                    <small class="form-hint">用于AI对话和聊天功能</small>
                                </div>
                                <div class="form-group">
                                    <label for="deepseekModel">默认模型</label>
                                    <select id="deepseekModel" name="deepseek_model">
                                        <option value="deepseek-chat">deepseek-chat</option>
                                        <option value="deepseek-reasoner">deepseek-reasoner</option>
                                    </select>
                                </div>
                                <div class="config-actions-single">
                                    <button type="button" class="btn-save-single" data-provider="deepseek">保存DeepSeek配置</button>
                                </div>
                            </div>

                            <!-- 火山引擎图片生成配置 -->
                            <div class="config-section">
                                <div class="section-header">
                                    <h4>🎨 火山引擎图片生成配置</h4>
                                    <span class="section-status" id="volcengineImageStatus">未配置</span>
                                </div>
                                <div class="form-group">
                                    <label for="volcengineImageKey">火山引擎API密钥</label>
                                    <div class="input-with-toggle">
                                        <input type="password" id="volcengineImageKey" name="volcengine_image_key" 
                                               placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
                                        <button type="button" class="toggle-visibility" data-target="volcengineImageKey">
                                            <span class="eye-icon">👁️</span>
                                        </button>
                                    </div>
                                    <small class="form-hint">用于AI图片生成功能</small>
                                </div>
                                <div class="form-group">
                                    <label for="volcengineImageModel">图片生成模型</label>
                                    <select id="volcengineImageModel" name="volcengine_image_model">
                                        <option value="doubao-seedream-3-0-t2i-250415">doubao-seedream-3-0-t2i-250415</option>
                                    </select>
                                </div>
                                <div class="config-actions-single">
                                    <button type="button" class="btn-save-single" data-provider="volcengine">保存图片生成配置</button>
                                </div>
                            </div>

                            <!-- 火山引擎TTS配置 -->
                            <div class="config-section">
                                <div class="section-header">
                                    <h4>🔊 火山引擎语音合成配置</h4>
                                    <span class="section-status" id="volcenttsTtsStatus">未配置</span>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="volcengineTtsAppId">App ID</label>
                                        <input type="text" id="volcengineTtsAppId" name="volcengine_tts_app_id" 
                                               placeholder="3581063476">
                                    </div>
                                    <div class="form-group">
                                        <label for="volcengineTtsAccessToken">Access Token</label>
                                        <div class="input-with-toggle">
                                            <input type="password" id="volcengineTtsAccessToken" name="volcengine_tts_access_token" 
                                                   placeholder="访问令牌">
                                            <button type="button" class="toggle-visibility" data-target="volcengineTtsAccessToken">
                                                <span class="eye-icon">👁️</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="volcengineTtsSecretKey">Secret Key</label>
                                        <div class="input-with-toggle">
                                            <input type="password" id="volcengineTtsSecretKey" name="volcengine_tts_secret_key" 
                                                   placeholder="密钥">
                                            <button type="button" class="toggle-visibility" data-target="volcengineTtsSecretKey">
                                                <span class="eye-icon">👁️</span>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label for="volcengineTtsCluster">Cluster</label>
                                        <input type="text" id="volcengineTtsCluster" name="volcengine_tts_cluster" 
                                               value="volcano_tts" readonly>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="volcengineTtsResourceId">Resource ID</label>
                                    <input type="text" id="volcengineTtsResourceId" name="volcengine_tts_resource_id" 
                                           value="volc.tts.default" readonly>
                                </div>
                                <div class="form-group">
                                    <label for="volcengineTtsVoice">默认音色</label>
                                    <select id="volcengineTtsVoice" name="volcengine_tts_voice">
                                        <option value="zh_female_wanqudashu_moon_bigtts">zh_female_wanqudashu_moon_bigtts</option>
                                        <option value="zh_male_jingqiangdaxiaosheng_moon_bigtts">zh_male_jingqiangdaxiaosheng_moon_bigtts</option>
                                        <option value="zh_female_tianmei_moon_bigtts">zh_female_tianmei_moon_bigtts</option>
                                    </select>
                                </div>
                                <div class="config-actions-single">
                                    <button type="button" class="btn-save-single" data-provider="volcengine_tts">保存TTS配置</button>
                                </div>
                            </div>

                            <!-- 其他API配置 -->
                            <div class="config-section">
                                <div class="section-header">
                                    <h4>🔧 其他API配置</h4>
                                    <span class="section-status" id="otherApiStatus">可选</span>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="openaiApiKey">OpenAI API密钥</label>
                                        <div class="input-with-toggle">
                                            <input type="password" id="openaiApiKey" name="openai_key" 
                                                   placeholder="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                                            <button type="button" class="toggle-visibility" data-target="openaiApiKey">
                                                <span class="eye-icon">👁️</span>
                                            </button>
                                        </div>
                                        <small class="form-hint">可选：用于OpenAI服务</small>
                                        <div class="config-actions-single">
                                            <button type="button" class="btn-save-single" data-provider="openai">保存OpenAI配置</button>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label for="claudeApiKey">Claude API密钥</label>
                                        <div class="input-with-toggle">
                                            <input type="password" id="claudeApiKey" name="claude_key" 
                                                   placeholder="sk-ant-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                                            <button type="button" class="toggle-visibility" data-target="claudeApiKey">
                                                <span class="eye-icon">👁️</span>
                                            </button>
                                        </div>
                                        <small class="form-hint">可选：用于Anthropic Claude服务</small>
                                        <div class="config-actions-single">
                                            <button type="button" class="btn-save-single" data-provider="claude">保存Claude配置</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label for="geminiApiKey">Gemini API密钥</label>
                                        <div class="input-with-toggle">
                                            <input type="password" id="geminiApiKey" name="gemini_key" 
                                                   placeholder="AIzaSyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                                            <button type="button" class="toggle-visibility" data-target="geminiApiKey">
                                                <span class="eye-icon">👁️</span>
                                            </button>
                                        </div>
                                        <small class="form-hint">可选：用于Google Gemini服务</small>
                                        <div class="config-actions-single">
                                            <button type="button" class="btn-save-single" data-provider="gemini">保存Gemini配置</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 配置操作 -->
                            <div class="config-actions">
                                <button type="button" id="loadCurrentConfigBtn" class="btn-secondary">加载当前配置</button>
                                <button type="button" id="testAllKeysBtn" class="btn-secondary">测试所有密钥</button>
                                <button type="submit" class="btn-primary">保存所有配置</button>
                            </div>
                        </form>
                        
                        <!-- 配置状态显示 -->
                        <div class="config-status-panel" id="configStatusPanel" style="display: none;">
                            <h4>配置状态</h4>
                            <div id="configStatusContent"></div>
                        </div>
                    </div>
                </div>
                
                <!-- 用户管理视图 -->
                <div id="users-view" class="view">
                    <div class="filter-bar">
                        <input type="text" id="searchUser" placeholder="搜索用户名或邮箱..." class="search-input">
                        <select id="filterUserRole" class="filter-select">
                            <option value="">所有角色</option>
                            <option value="admin">管理员</option>
                            <option value="user">普通用户</option>
                        </select>
                        <select id="filterUserStatus" class="filter-select">
                            <option value="">所有状态</option>
                            <option value="active">活跃</option>
                            <option value="inactive">非活跃</option>
                        </select>
                    </div>
                    
                    <div class="data-table-container">
                        <table class="data-table" id="usersTable">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="selectAllUsers"></th>
                                    <th>ID</th>
                                    <th>头像</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>角色</th>
                                    <th>注册时间</th>
                                    <th>最后登录</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                <tr>
                                    <td colspan="9" style="text-align: center;">加载中...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="pagination" id="usersPagination">
                        <!-- JS填充分页 -->
                    </div>
                </div>
                
                <!-- 社区图片管理视图 -->
                <div id="shared-images-view" class="view">
                    <div class="filter-bar">
                        <input type="text" id="searchSharedImage" placeholder="搜索图片标题..." class="search-input">
                        <select id="filterImageCategory" class="filter-select">
                            <option value="">所有分类</option>
                            <option value="风景">风景</option>
                            <option value="人物">人物</option>
                            <option value="动物">动物</option>
                            <option value="建筑">建筑</option>
                            <option value="艺术">艺术</option>
                            <option value="其他">其他</option>
                        </select>
                        <select id="filterImageUser" class="filter-select">
                            <option value="">所有用户</option>
                        </select>
                    </div>
                    
                    <div class="shared-images-grid" id="sharedImagesGrid">
                        <div class="loading-placeholder">加载中...</div>
                    </div>
                    
                    <div class="pagination" id="sharedImagesPagination">
                        <!-- JS填充分页 -->
                    </div>
                </div>
                
                <!-- 文件管理视图 -->
                <div id="file-management-view" class="view">
                    <div class="file-stats-panel">
                        <h3>文件统计信息</h3>
                        <div class="stats-grid">
                            <div class="stat-card">
                                <h4>总文件数</h4>
                                <span id="totalFiles" class="stat-value">-</span>
                            </div>
                            <div class="stat-card">
                                <h4>使用中文件</h4>
                                <span id="usedFiles" class="stat-value">-</span>
                            </div>
                            <div class="stat-card">
                                <h4>未使用文件</h4>
                                <span id="unusedFiles" class="stat-value">-</span>
                            </div>
                            <div class="stat-card">
                                <h4>总大小</h4>
                                <span id="totalSize" class="stat-value">-</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="file-cleanup-panel">
                        <h3>文件清理</h3>
                        <div class="cleanup-actions">
                            <button id="previewCleanupBtn" class="btn-secondary">预览清理</button>
                            <button id="executeCleanupBtn" class="btn-danger" disabled>执行清理</button>
                        </div>
                        
                        <div id="cleanupResults" class="cleanup-results" style="display: none;">
                            <h4>清理结果</h4>
                            <div id="cleanupResultsContent"></div>
                        </div>
                        
                        <div id="unusedFilesList" class="unused-files-list" style="display: none;">
                            <h4>未使用的文件</h4>
                            <div id="unusedFilesContent"></div>
                        </div>
                    </div>
                </div>
                
                <!-- 系统设置视图 -->
                <div id="system-view" class="view">
                    <div class="settings-panel">
                        <h3>系统配置</h3>
                        <form id="systemConfigForm">
                            <div class="form-group">
                                <label for="adminRegisterKey">管理员注册密钥</label>
                                <input type="text" id="adminRegisterKey" name="adminRegisterKey">
                            </div>
                            <div class="form-group">
                                <label for="maxUploadSize">最大上传文件大小 (MB)</label>
                                <input type="number" id="maxUploadSize" name="maxUploadSize" min="1" max="100">
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn-primary">保存设置</button>
                            </div>
                        </form>
                    </div>
                    
                    <div class="settings-panel">
                        <h3>开发工具</h3>
                        <div class="dev-tools-section">
                            <p class="section-description">开发和测试相关的工具和文档。</p>
                            <div class="form-group">
                                <button type="button" class="btn-secondary" onclick="showApiDocumentation()">
                                    📖 查看接口测试文档
                                </button>
                                <small class="help-text">查看所有API接口的详细测试信息，包括URL、请求方式、参数示例等。</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="settings-panel">
                        <h3>数据管理</h3>
                        <div class="data-export-section">
                            <p class="section-description">导出当前数据库中的数据，用于开发初始数据表或数据备份。</p>
                            <div class="export-options">
                                <div class="form-group">
                                    <label>选择要导出的数据表：</label>
                                    <div class="checkbox-group">
                                        <label class="checkbox-item">
                                            <input type="checkbox" id="exportUsers" checked>
                                            <span>用户数据 (Users)</span>
                                        </label>
                                        <label class="checkbox-item">
                                            <input type="checkbox" id="exportAiRoles" checked>
                                            <span>AI角色 (AIRoles)</span>
                                        </label>
                                        <label class="checkbox-item">
                                            <input type="checkbox" id="exportApiKeys" checked>
                                            <span>API密钥 (ApiKeys)</span>
                                        </label>
                                        <label class="checkbox-item">
                                            <input type="checkbox" id="exportSharedImages" checked>
                                            <span>社区图片 (SharedImages)</span>
                                        </label>
                                        <label class="checkbox-item">
                                            <input type="checkbox" id="exportInteractions" checked>
                                            <span>交互记录 (Interactions)</span>
                                        </label>
                                        <label class="checkbox-item">
                                            <input type="checkbox" id="exportUserLikes" checked>
                                            <span>用户点赞 (UserLikes)</span>
                                        </label>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="exportFormat">导出格式：</label>
                                    <select id="exportFormat" class="filter-select">
                                        <option value="sql">SQL插入语句</option>
                                        <option value="json">JSON格式</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <button type="button" id="exportDataBtn" class="btn-primary">导出数据</button>
                                    <button type="button" id="exportSchemaBtn" class="btn-secondary">导出表结构</button>
                                </div>
                            </div>
                            <div id="exportStatus" class="export-status" style="display: none;">
                                <div class="loading-indicator">
                                    <span>正在导出数据...</span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="data-import-guide" style="margin-top: 30px; border: 1px solid #e8e8e8; padding: 20px; border-radius: 5px; background-color: #f9f9f9;">
                            <h4 style="margin-top: 0; color: #1890ff;">数据库部署与导入指南</h4>
                            
                            <div class="import-steps" style="margin-top: 15px;">
                                <h5 style="font-weight: 600; margin-bottom: 10px;">1. 配置环境变量</h5>
                                <p>复制项目根目录下的<code>.env.example</code>文件为<code>.env</code>，并配置以下关键参数：</p>
                                <div class="code-block" style="background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: monospace; margin-bottom: 15px;">
                                    <pre style="margin: 0; white-space: pre-wrap;"># 服务器配置
PORT=3000
JWT_SECRET=your_jwt_secret_here
ADMIN_REGISTER_KEY=admin_secret_key_12345

# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_NAME=mars_intelligence
DB_USER=root
DB_PASSWORD=your_password_here

# API密钥加密配置
API_KEY_ENCRYPTION_SECRET=your-secure-32-character-encryption-key</pre>
                                </div>
                                
                                <h5 style="font-weight: 600; margin-bottom: 10px;">2. 安装依赖</h5>
                                <div class="code-block" style="background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: monospace; margin-bottom: 15px;">
                                    <pre style="margin: 0;">npm install</pre>
                                </div>
                                
                                <h5 style="font-weight: 600; margin-bottom: 10px;">3. 导入数据（可选）</h5>
                                <p>使用Navicat或其他MySQL管理工具导入导出的SQL文件：</p>
                                <ol style="margin-left: 20px; margin-bottom: 15px;">
                                    <li>打开Navicat并连接到MySQL服务器</li>
                                    <li>右键点击连接，选择"新建数据库"，创建名为<code>mars_intelligence</code>的数据库</li>
                                    <li>右键点击新创建的数据库，选择"运行SQL文件"</li>
                                    <li>选择导出的SQL文件并执行</li>
                                </ol>
                                <p><strong>注意：</strong>启动服务器时会自动创建数据库表结构，如果只需要空数据库可以跳过导入步骤。</p>
                                
                                <h5 style="font-weight: 600; margin-bottom: 10px;">4. 启动服务</h5>
                                <div class="code-block" style="background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: monospace; margin-bottom: 15px;">
                                    <pre style="margin: 0;">npm start</pre>
                                </div>
                                <p>或使用开发模式启动（自动重载）：</p>
                                <div class="code-block" style="background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: monospace; margin-bottom: 15px;">
                                    <pre style="margin: 0;">npm run dev</pre>
                                </div>
                                
                                <h5 style="font-weight: 600; margin-bottom: 10px;">5. 创建管理员账号</h5>
                                <p>如果没有导入管理员账号数据，可以通过API创建：</p>
                                <div class="code-block" style="background: #f0f0f0; padding: 10px; border-radius: 4px; font-family: monospace; margin-bottom: 15px;">
                                    <pre style="margin: 0; white-space: pre-wrap;">curl -X POST http://localhost:3000/api/auth/admin/register \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123", "email": "admin@example.com", "adminKey": "admin_secret_key_12345"}'</pre>
                                </div>
                                <p><small>注：adminKey需要与.env文件中设置的ADMIN_REGISTER_KEY值一致。</small></p>
                                
                                <h5 style="font-weight: 600; margin-bottom: 10px;">6. 访问管理系统</h5>
                                <p>启动服务后，访问：<a href="http://localhost:3000/admin/" target="_blank">http://localhost:3000/admin/</a></p>
                            </div>
                            
                            <div class="import-notes" style="margin-top: 20px; padding: 10px; background-color: #e6f7ff; border-left: 4px solid #1890ff; border-radius: 2px;">
                                <h5 style="margin-top: 0;">注意事项：</h5>
                                <ul style="padding-left: 20px; margin-bottom: 0;">
                                    <li><strong>自动创建表结构：</strong>服务器启动时会自动创建必要的数据库表结构</li>
                                    <li><strong>数据导入：</strong>只有在需要预设数据时才需要导入SQL文件</li>
                                    <li><strong>图片资源：</strong>图片等静态资源需要单独复制到对应目录</li>
                                    <li><strong>环境变量：</strong>确保.env文件中的数据库连接信息正确</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 接口测试文档视图 -->
                <div id="api-docs-view" class="view" style="display: none;">
                    <div class="api-docs-container">
                        <div class="api-docs-header">
                            <h3>Mars Intelligence 接口测试文档</h3>
                            <button type="button" class="btn-secondary" onclick="hideApiDocumentation()">返回系统设置</button>
                        </div>
                        <div class="api-docs-content" id="apiDocsContent">
                            <!-- 接口文档内容将在这里动态加载 -->
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 模态框 - 创建/编辑AI角色 -->
    <div id="aiRoleModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">创建新AI角色</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <form id="aiRoleForm">
                    <input type="hidden" id="aiRoleId">
                    <div class="form-group">
                        <label for="name">角色名称</label>
                        <input type="text" id="name" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="description">角色描述</label>
                        <textarea id="description" name="description" rows="3" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="type">角色类型</label>
                        <select id="type" name="type" required>
                            <option value="assistant">通用助手</option>
                            <option value="tutor">教育导师</option>
                            <option value="entertainment">娱乐伙伴</option>
                            <option value="other">其他类型</option>
                            <option value="text-to-image">文生图</option>

                        </select>
                    </div>
                    <div class="form-group">
                        <label for="apiProvider">API提供商</label>
                        <input type="text" id="apiProvider" name="api_provider" placeholder="例如: OpenAI, Azure, 自定义等" required>
                        <small class="form-hint">请填写API提供商名称，例如OpenAI、Anthropic、自定义等</small>
                        <div class="api-provider-suggestions">
                            <button type="button" class="suggestion-btn" data-value="OpenAI">OpenAI</button>
                            <button type="button" class="suggestion-btn" data-value="Azure">Azure</button>
                            <button type="button" class="suggestion-btn" data-value="Anthropic">Anthropic</button>
                            <button type="button" class="suggestion-btn" data-value="Gemini">Gemini</button>
                            <button type="button" class="suggestion-btn" data-value="Volcengine">Volcengine</button>
                            <button type="button" class="suggestion-btn" data-value="deepseek">deepseek</button>
                            <button type="button" class="suggestion-btn" data-value="Custom">自定义</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="apiConfig">API配置 (JSON)</label>
                        <textarea id="apiConfig" name="api_config" rows="3" required>{
  "model": "gpt-3.5-turbo"
}</textarea>
                    </div>
                    <div class="form-group">
                        <label for="systemPrompt">系统提示词</label>
                        <textarea id="systemPrompt" name="system_prompt" rows="5" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="avatar">头像</label>
                        <div class="avatar-upload-container">
                            <div class="avatar-preview" id="avatarPreview">
                                <img id="avatarPreviewImg" src="" alt="头像预览" style="display: none;">
                                <div class="upload-placeholder" id="uploadPlaceholder">
                                    <span>点击上传头像</span>
                                </div>
                            </div>
                            <input type="file" id="avatarFile" accept="image/*" style="display: none;">
                            <input type="hidden" id="avatar" name="avatar" required>
                            <div class="upload-actions">
                                <button type="button" class="btn-secondary" id="selectAvatarBtn">选择文件</button>
                                <button type="button" class="btn-secondary" id="removeAvatarBtn" style="display: none;">移除</button>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn-primary" id="saveAiRoleBtn">保存</button>
                        <button type="button" class="btn-secondary" id="cancelAiRoleBtn">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 模态框 - 创建/编辑API密钥 -->
    <div id="apiKeyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="apiKeyModalTitle">创建新API密钥</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <form id="apiKeyForm">
                    <input type="hidden" id="apiKeyId">
                    <div class="form-group">
                        <label for="apiKeyName">密钥名称</label>
                        <input type="text" id="apiKeyName" name="name" required placeholder="例如：OpenAI生产密钥">
                    </div>
                    <div class="form-group">
                        <label for="apiKeyProvider">API提供商</label>
                        <input type="text" id="apiKeyProvider" name="provider" required placeholder="例如：openai, claude, gemini, deepseek, zhipu">
                        <small class="form-hint">请输入API提供商名称，支持任意提供商</small>
                        <div class="provider-suggestions">
                            <span class="suggestion-label">常用提供商：</span>
                            <button type="button" class="provider-btn" onclick="document.getElementById('apiKeyProvider').value='openai'">OpenAI</button>
                            <button type="button" class="provider-btn" onclick="document.getElementById('apiKeyProvider').value='claude'">Claude</button>
                            <button type="button" class="provider-btn" onclick="document.getElementById('apiKeyProvider').value='gemini'">Gemini</button>
                            <button type="button" class="provider-btn" onclick="document.getElementById('apiKeyProvider').value='deepseek'">DeepSeek</button>
                            <button type="button" class="provider-btn" onclick="document.getElementById('apiKeyProvider').value='zhipu'">智谱AI</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="apiKeyValue">API密钥</label>
                        <input type="password" id="apiKeyValue" name="api_key" required placeholder="请输入API密钥">
                        <small class="form-hint">密钥将被加密存储，请确保密钥的准确性</small>
                    </div>
                    <div class="form-group">
                        <label for="apiKeyDailyLimit">每日使用限制</label>
                        <input type="number" id="apiKeyDailyLimit" name="daily_limit" min="0" placeholder="留空表示无限制">
                    </div>
                    <div class="form-group">
                        <label for="apiKeyMonthlyLimit">每月使用限制</label>
                        <input type="number" id="apiKeyMonthlyLimit" name="monthly_limit" min="0" placeholder="留空表示无限制">
                    </div>
                    <div class="form-group">
                        <label for="apiKeyNotes">备注信息</label>
                        <textarea id="apiKeyNotes" name="notes" rows="3" placeholder="可选的备注信息"></textarea>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="apiKeyIsActive" name="is_active" checked>
                            启用此API密钥
                        </label>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn-primary" id="saveApiKeyBtn">保存</button>
                        <button type="button" class="btn-secondary" id="cancelApiKeyBtn">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 模态框 - 创建/编辑用户 -->
    <div id="userModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="userModalTitle">创建新用户</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" id="userId">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" name="username" required placeholder="请输入用户名">
                    </div>
                    <div class="form-group">
                        <label for="email">邮箱</label>
                        <input type="email" id="email" name="email" placeholder="请输入邮箱地址">
                    </div>
                    <div class="form-group" id="passwordGroup">
                        <label for="password">密码</label>
                        <input type="password" id="password" name="password" placeholder="请输入密码">
                        <small class="form-hint">编辑用户时留空表示不修改密码</small>
                    </div>
                    <div class="form-group">
                        <label for="userAvatar">头像</label>
                        <div class="avatar-upload-container">
                            <div class="avatar-preview" id="userAvatarPreview">
                                <img id="userAvatarPreviewImg" src="" alt="头像预览" style="display: none;">
                                <div class="upload-placeholder" id="userUploadPlaceholder">
                                    <span>点击上传头像</span>
                                </div>
                            </div>
                            <input type="file" id="userAvatarFile" accept="image/*" style="display: none;">
                            <input type="hidden" id="userAvatar" name="avatar">
                            <div class="upload-actions">
                                <button type="button" class="btn-secondary" id="selectUserAvatarBtn">选择文件</button>
                                <button type="button" class="btn-secondary" id="removeUserAvatarBtn" style="display: none;">移除</button>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="isAdmin" name="isAdmin">
                            管理员权限
                        </label>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn-primary" id="saveUserBtn">保存</button>
                        <button type="button" class="btn-secondary" id="cancelUserBtn">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 模态框 - 用户详情 -->
    <div id="userDetailModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>用户详情</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div class="user-detail-container">
                    <div class="user-avatar-section">
                        <img id="detailUserAvatar" src="" alt="用户头像" class="user-avatar-large">
                    </div>
                    <div class="user-info-section">
                        <div class="info-item">
                            <label>用户ID:</label>
                            <span id="detailUserId"></span>
                        </div>
                        <div class="info-item">
                            <label>用户名:</label>
                            <span id="detailUsername"></span>
                        </div>
                        <div class="info-item">
                            <label>邮箱:</label>
                            <span id="detailUserEmail"></span>
                        </div>
                        <div class="info-item">
                            <label>角色:</label>
                            <span id="detailUserRole"></span>
                        </div>
                        <div class="info-item">
                            <label>注册时间:</label>
                            <span id="detailUserCreatedAt"></span>
                        </div>
                        <div class="info-item">
                            <label>最后登录:</label>
                            <span id="detailUserLastLogin"></span>
                        </div>
                    </div>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn-primary" id="editUserFromDetailBtn">编辑用户</button>
                    <button type="button" class="btn-secondary" id="closeUserDetailBtn">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 模态框 - 查看社区图片详情 -->
    <div id="sharedImageModal" class="modal">
        <div class="modal-content modal-large">
            <div class="modal-header">
                <h3 id="sharedImageModalTitle">图片详情</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div class="image-detail-container">
                    <div class="image-preview">
                        <img id="sharedImagePreview" src="" alt="图片预览">
                    </div>
                    <div class="image-info">
                        <div class="info-item">
                            <label>标题:</label>
                            <span id="sharedImageTitle"></span>
                        </div>
                        <div class="info-item">
                            <label>描述:</label>
                            <p id="sharedImageDescription"></p>
                        </div>
                        <div class="info-item">
                            <label>分类:</label>
                            <span id="sharedImageCategory"></span>
                        </div>
                        <div class="info-item">
                            <label>标签:</label>
                            <div id="sharedImageTags"></div>
                        </div>
                        <div class="info-item">
                            <label>上传用户:</label>
                            <span id="sharedImageUser"></span>
                        </div>
                        <div class="info-item">
                            <label>AI角色:</label>
                            <span id="sharedImageAiRole"></span>
                        </div>
                        <div class="info-item">
                            <label>点赞数:</label>
                            <span id="sharedImageLikes"></span>
                        </div>
                        <div class="info-item">
                            <label>创建时间:</label>
                            <span id="sharedImageCreatedAt"></span>
                        </div>
                        <div class="info-item">
                            <label>操作:</label>
                            <div class="image-actions">
                                <button id="deleteSharedImageBtn" class="btn-danger">删除图片</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 模态框 - 查看AI角色详情及在线调用 -->
    <div id="aiRoleViewModal" class="modal">
        <div class="modal-content modal-large">
            <div class="modal-header">
                <h3 id="viewModalTitle">AI角色详情</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div class="view-container">
                    <!-- 左侧角色信息 -->
                    <div class="view-info">
                        <div class="view-avatar">
                            <img id="viewAvatar" src="" alt="头像">
                        </div>
                        <h3 id="viewName"></h3>
                        <div class="info-item">
                            <label>类型:</label>
                            <span id="viewType"></span>
                        </div>
                        <div class="info-item">
                            <label>API提供商:</label>
                            <span id="viewProvider"></span>
                        </div>
                        <div class="info-item">
                            <label>模型:</label>
                            <span id="viewModel" style="color: #1890ff; font-weight: bold;"></span>
                        </div>
                        <div class="info-item">
                            <label>描述:</label>
                            <p id="viewDescription"></p>
                        </div>
                        <div class="info-item">
                            <label>系统提示词:</label>
                            <pre id="viewSystemPrompt"></pre>
                        </div>
                        <div class="info-item">
                            <label>API配置:</label>
                            <pre id="viewApiConfig"></pre>
                        </div>
                        <div class="info-item">
                            <label>创建时间:</label>
                            <span id="viewCreatedAt"></span>
                        </div>
                    </div>

                    <!-- 测试功能已移除 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 加载通用JavaScript -->
    <script src="../admin.js"></script>
    <script src="../api-config-features.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            initApiConfigFeatures();
        });
    </script>
    <script>
        // 辅助函数：检查是否已登录，从多种存储中获取token
        function checkLoggedIn() {
            console.log('dashboard.html - 检查登录状态...');
            
            let token = null;
            let source = '';
            
            // 按优先级检查各种存储
            if (localStorage && localStorage.getItem('adminToken')) {
                token = localStorage.getItem('adminToken');
                source = 'localStorage';
            } else if (sessionStorage && sessionStorage.getItem('adminToken')) {
                token = sessionStorage.getItem('adminToken');
                source = 'sessionStorage';
            } else {
                // 检查cookie
                const match = document.cookie.match(/adminToken=([^;]+)/);
                if (match) {
                    token = match[1];
                    source = 'cookies';
                }
            }
            
            if (token) {
                console.log(`dashboard.html - 从 ${source} 读取到token: ${token.substring(0, 15)}...`);
                return token;
            } else {
                console.warn('dashboard.html - 未找到存储的token');
                return null;
            }
        }
        
        // 页面加载完成后检查认证状态
        document.addEventListener('DOMContentLoaded', function() {
            console.log('dashboard.html - 页面加载完成，开始检查认证状态');
            
            // 显示加载状态
            const mainContent = document.querySelector('.main-content');
            if (mainContent) {
                const loadingDiv = document.createElement('div');
                loadingDiv.id = 'auth-loading';
                loadingDiv.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(255,255,255,0.8);display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:9999;';
                loadingDiv.innerHTML = `
                    <div style="border:4px solid #f3f3f3;border-top:4px solid #3498db;border-radius:50%;width:50px;height:50px;animation:spin 2s linear infinite;"></div>
                    <p style="margin-top:20px;font-size:16px;">正在验证登录状态...</p>
                    <style>@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}</style>
                `;
                document.body.appendChild(loadingDiv);
            }
            
            // 检查认证状态
            const token = checkLoggedIn();
            
            if (!token) {
                // 未登录，重定向到登录页
                console.error('dashboard.html - 未检测到登录状态，准备重定向到登录页');
                
                if (document.getElementById('auth-loading')) {
                    document.getElementById('auth-loading').innerHTML = `
                        <p style="color:red;font-size:16px;margin-bottom:20px;">未检测到登录状态</p>
                        <button id="go-login" style="padding:8px 16px;background:#1890ff;color:white;border:none;border-radius:4px;cursor:pointer;">前往登录页</button>
                    `;
                    document.getElementById('go-login').addEventListener('click', function() {
                        window.location.href = '/admin/login.html';
                    });
                } else {
                    alert('未检测到登录状态，将跳转到登录页');
                    window.location.href = '/admin/login.html';
                }
                return;
            }
            
            // 移除加载状态显示
            if (document.getElementById('auth-loading')) {
                document.getElementById('auth-loading').remove();
            }
            
            console.log('dashboard.html - 已检测到登录状态，准备初始化管理界面');
            
            // 测试token有效性
            fetch('/api/airoles', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                credentials: 'same-origin'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP 错误状态: ${response.status}`);
                }
                return response.json();
            })
            .then(rolesData => {
                console.log('token有效，获取到AI角色数据', rolesData);
                
                // 设置默认管理员名称
                document.getElementById('currentUser').textContent = '管理员用户';
                
                // 确保调用初始化函数
                if (typeof initDashboard === 'function') {
                    initDashboard();
                } else {
                    console.error('找不到初始化函数，可能是admin.js未正确加载');
                    alert('加载管理界面失败，请刷新页面重试');
                    
                    // 提供重新加载脚本的选项
                    const scriptEl = document.createElement('script');
                    scriptEl.src = '../admin.js?t=' + new Date().getTime(); // 添加时间戳避免缓存
                    scriptEl.onload = function() {
                        console.log('已重新加载admin.js，尝试再次初始化');
                        if (typeof initDashboard === 'function') {
                            initDashboard();
                        }
                    };
                    scriptEl.onerror = function() {
                        console.error('重新加载admin.js失败');
                        alert('无法加载必要脚本，请检查网络连接后刷新页面');
                    };
                    document.body.appendChild(scriptEl);
                }
            })
            .catch(error => {
                console.error('验证token时出错:', error);
                alert('验证登录状态失败，请重新登录');
                
                // 清除所有token
                if (localStorage) localStorage.removeItem('adminToken');
                if (sessionStorage) sessionStorage.removeItem('adminToken');
                document.cookie = 'adminToken=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT';
                
                window.location.href = '/admin/login.html';
            });
        });
    </script>
</body>
</html>